<template>
  <div class="left-column">
    <div class="column-card">
      <!-- 头部保持不变 -->
      <div class="card-header">
        <div style="display: flex;align-items: center;gap: 3px">
          <i class="fas fa-calendar-alt" aria-hidden="true"/>
          <h3>今日抗遗忘</h3>
        </div>
        <div class="view-switcher">
          <el-button
            icon="fa-solid fa-list-ol"
            size="mini"
            :class="{ 'look-view-type': true }"
            @click="$emit('changeAntiForgetView', 'list')"
          >
            列表视图
          </el-button>
          <el-button
            icon="fa-solid fa-flag"
            size="mini"
            :class="{ 'active': true }"
            @click="$router.push({ path: '/course', query: { childMenu: 1 }})"
          >
            全部抗遗忘
          </el-button>
          <el-button
            icon="fa-solid fa-arrows-rotate"
            size="mini"
            :class="{ 'reload-data': true }"
            @click="refreshSchedule"
          >
            刷新
          </el-button>
          <span class="badge">{{ antiForgetCount }}</span>
        </div>
      </div>

      <div class="calendar-content">
        <ul class="schedule-list">
          <!-- 日期分组 -->
          <div v-for="(dateItem,dateKey,indexDate) in courses" :key="indexDate" class="date-item-div">
            <!-- 日期标题 -->
            <div class="date-title">
              <span class="date-text">{{ dateKey }}</span>
              <span class="date-count">{{ getDateCourseCount(dateItem) }}节抗遗忘</span>
            </div>

            <!-- 学生分组 -->
            <div v-for="(studentItem,studentKey,indexStu) in dateItem" :key="indexStu" class="date-student-div">
              <!-- 学生信息+聚合复习按钮 -->
              <div class="student-header">
                <div>
                  <span class="student-name">{{ studentItem[0].studentName }}</span>
                  <span class="student-count">{{ studentItem.length }}节</span>
                </div>
                <el-button
                  v-if="studentItem.length > 1 && isAntiForgetListUnfinished(studentItem)"
                  size="mini"
                  class="aggregate-btn"
                  @click="handleReviewBatch(studentItem)"
                >聚合复习
                </el-button>
                <el-button
                  v-if="studentItem.length > 1 && isAntiForgetListFinished(studentItem)"
                  size="mini"
                  class="aggregate-btn-report"
                  @click="handleReviewBatchReport(studentItem)"
                >聚合报告
                </el-button>
              </div>

              <!-- 抗遗忘列表 -->
              <ul class="student-course-list">
                <li v-for="(item,index) in studentItem" :key="item.id" class="schedule-item">
                  <span class="time">{{ item.name }}</span>
                  <span class="content">【{{ item.actualStartTime ? item.actualStartTime.substring(0, 16) : '' }}】</span>
                  <span class="platform">线上会议</span>
                  <span v-if="item.status==='0'" class="platform-wait">待复习</span>
                  <span v-if="item.status==='1'" class="platform-wait platform-close">已取消</span>
                  <span v-if="item.status==='2'" class="platform-wait platform-end">已完成</span>
                  <span v-if="item.status==='3'" class="platform-wait platform-postponement">已延期</span>
                  <div class="forget-div-btn">
                    <i
                      v-if="item.status==='0' || item.status==='3'"
                      class="fa-solid fa-trash forget-del"
                      aria-hidden="true"
                      @click="delForget(item)"
                    />
                    <el-button class="action-btn" @click="handleCourse(item)">
                      <i v-if="item.status!=='2'" class="fas fa-video" aria-hidden="true"/>
                      <i v-if="item.status==='2'" class="fa-solid fa-print" aria-hidden="true"/>
                      <span v-if="item.status==='0' || item.status==='3'">进入复习</span>
                      <span v-if="item.status==='2'">打印</span>
                    </el-button>
                    <el-button v-if="item.status==='2'" class="action-btn" @click="handleAntiFeedback(item)">
                      <i class="fa-solid fa-person-military-pointing"/>
                      <span>反馈</span>
                    </el-button>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </ul>
      </div>

      <!-- 空状态 -->
      <div v-if="isCoursesEmpty" class="empty-state">
        <i class="fas fa-calendar-day" aria-hidden="true"/>
        <p>今日暂无抗遗忘</p>
      </div>
    </div>
  </div>
</template>

<script>
import { deleteAntiForget, pullTodayAntiForgetList, startAntiForget, startAntiForgetBatch } from '@/api/antiForget'

export default {
  name: 'AntiForgetColumn',
  data() {
    return {
      courses: [],
      antiForgetCount: 0
    }
  },
  computed: {
    // 判断courses是否为空（对象类型）
    isCoursesEmpty() {
      if (!this.courses || typeof this.courses !== 'object') return true
      // 检查所有日期分组下是否有抗遗忘
      return Object.values(this.courses).every(dateItem => {
        return Object.values(dateItem).every(studentItem => studentItem.length === 0)
      })
    }
  },
  mounted() {
    this.refreshSchedule()
  },
  methods: {
    handleAntiFeedback(item) {
      window.open(
        `${window.location.origin}${window.location.pathname}#/antiForgetFeedback?antiForgetId=${item.id}`,
        '_blank',
        'width=600,height=800,top=100,left=200'
      )
    },
    async handleCourse(item) {
      if (item.status === '0' || item.status === '3') {
        await startAntiForget({ antiForgetId: item.id })
        window.open(
          `${window.location.origin}${window.location.pathname}#/antiForget?q1=${item.id}&cid=${item.courseId}`,
          '_blank',
          'width=600,height=800,top=100,left=200'
        )
      } else if (item.status === '2') {
        window.open(`${window.location.origin}${window.location.pathname}#/print?cid=${item.courseId}&antiForgetId=${item.id}`)
      }
    },
    async handleReviewBatch(antiForgetList) {
      const idArr = antiForgetList.map(item => item.id)
      await startAntiForgetBatch(idArr)
      const params = []
      antiForgetList.forEach(item => {
        params.push({
          antiForgetId: item.id,
          cid: item.courseId
        })
      })

      window.open(
        `${window.location.origin}${window.location.pathname}#/antiForget?idArr=${JSON.stringify(params)}`,
        '_blank',
        'width=600,height=800,top=100,left=200'
      )
    },
    handleReviewBatchReport(antiForgetList) {
      const idArr = antiForgetList.map(item => item.id)
      window.open(
        `${window.location.origin}${window.location.pathname}#/antiForgetFeedback?antiForgetIdArr=${JSON.stringify(idArr)}`,
        '_blank',
        'width=600,height=800,top=100,left=200'
      )
    },
    // 计算某个日期分组下的总抗遗忘数
    getDateCourseCount(dateItem) {
      return Object.values(dateItem).reduce((total, studentItem) => total + studentItem.length, 0)
    },
    // 判断抗遗忘列表未完成的个数是否大于1
    isAntiForgetListUnfinished(antiForgetList) {
      if (!antiForgetList) {
        return false
      }
      return antiForgetList.filter(item => item.status !== '2').length > 1
    },
    // 判断抗遗忘列表是否完成
    isAntiForgetListFinished(antiForgetList) {
      if (!antiForgetList) {
        return true
      }
      return antiForgetList.every(item => item.status === '2')
    },
    async delForget(item) {
      this.$confirm('确定要删除这节抗遗忘吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteAntiForget({ antiForgetId: item.id })
        await this.refreshSchedule()
        this.$notify.success('抗遗忘已删除')
      }).catch(() => {
        this.$notify.info('已取消删除')
      })
    },
    // 刷新数据
    async refreshSchedule() {
      this.courses = await pullTodayAntiForgetList()
      this.antiForgetCount = this.courses.length
      const dateGroupedData = this.groupCoursesByAntiDate(this.courses)
      this.courses = this.groupByDateThenStudent(dateGroupedData)
    },
    /**
     * 按antiDate的年月日分组抗遗忘数据
     * @param {Array} courses - 原始抗遗忘数组（格式如示例）
     * @returns {Object} 分组后的数据，键为"YYYY-MM-DD"格式日期，值为对应抗遗忘数组
     */
    groupCoursesByAntiDate(courses) {
      // 边界处理：若输入不是数组或为空，返回空对象
      if (!Array.isArray(courses) || courses.length === 0) {
        return {}
      }

      // 遍历数组，按年月日分组
      return courses.reduce((groupedObj, course) => {
        // 截取antiDate的年月日部分（前10个字符）作为分组键
        const dateKey = course.antiDate?.substring(0, 10)

        // 若course无antiDate字段，归入"未分类"组
        const key = dateKey || '未分类'

        // 初始化该日期分组（若不存在）
        if (!groupedObj[key]) {
          groupedObj[key] = []
        }

        // 将当前抗遗忘加入对应分组
        groupedObj[key].push(course)

        return groupedObj
      }, {})
    },
    /**
     * 保留日期分组层级，在每个日期下再按studentId分类抗遗忘
     * @param {Object} dateGroupedData - 按日期分组的原始数据（格式如示例）
     * @returns {Object} 三层嵌套结构：{ 日期: { studentId: [抗遗忘数组], ... }, ... }
     */
    groupByDateThenStudent(dateGroupedData) {
      // 边界处理：非对象或空数据返回空对象
      if (typeof dateGroupedData !== 'object' || dateGroupedData === null) {
        return {}
      }

      // 遍历每个日期分组，在内部按studentId二次分组
      return Object.keys(dateGroupedData).reduce((result, dateKey) => {
        // 获取当前日期下的所有抗遗忘
        const dateCourses = dateGroupedData[dateKey]
        if (!Array.isArray(dateCourses)) {
          // 若当前日期下不是数组，直接跳过（避免异常数据）
          result[dateKey] = {}
          return result
        }

        // 对当前日期的抗遗忘按studentId分组
        const studentGrouped = dateCourses.reduce((studentObj, course) => {
          const studentId = course.studentId || '未知学生' // 处理无studentId的情况
          if (!studentObj[studentId]) {
            studentObj[studentId] = []
          }
          studentObj[studentId].push(course)
          return studentObj
        }, {})

        // 将按学生分组的结果存入当前日期下
        result[dateKey] = studentGrouped
        return result
      }, {})
    }
  }
}
</script>

<style scoped>
.left-column {
  min-width: 750px;
  box-sizing: border-box;
  margin-bottom: 20px;
}

.column-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(8, 8, 8, 0.15);
  padding: 15px 20px;
  background-color: #fff;
}

.date-text {
  font-size: 15px;
  font-weight: 500;
  color: #3498db;
  margin-right: 12px;
}

.date-count {
  font-size: 12px;
  color: #666;
  background-color: #e8f4ff;
  padding: 2px 8px;
  border-radius: 12px;
}

/* 学生分组样式 */
.date-student-div {
  margin-left: 20px;
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
  /*  border-left: 6px solid transparent;
    border-left-color: #ff5e06;
    border-radius: 12px;*/
}

/* 学生头部（姓名+按钮） */
.student-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 16px;
  background-color: #fff8f0;
  border-left: 6px solid #ff5e06;
  margin-bottom: 8px;
}

.student-name {
  font-size: 14px;
  font-weight: 500;
  color: #ff5e06;
}

.student-count {
  font-size: 12px;
  color: #888;
  margin-left: 10px;
}

/* 聚合复习按钮 */
.aggregate-btn {
  padding: 2px 10px;
  border-radius: 6px;
  background-color: #ff5e06;
  color: #fff;
  border: none;
  font-size: 12px;
}

.aggregate-btn:hover {
  background-color: #e05200;
  color: #fff;
}

.aggregate-btn-report {
  padding: 2px 10px;
  border-radius: 6px;
  background-color: #12884a;
  color: #fff;
  border: none;
  font-size: 12px;
}

/* 学生抗遗忘列表容器 */
.student-course-list {
  list-style: none;
  padding: 0;
  margin: 0 0 0 16px;
}

/* 抗遗忘项样式调整 */
.schedule-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px dashed #f0f0f0;
  align-items: center;
  margin-left: 10px;
}

/* 移除重复的学生名称显示（已在student-header展示） */
.schedule-item .platform:first-of-type {
  display: none;
}

/* 调整按钮间距 */
.forget-div-btn {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
}

.forget-del {
  position: relative;
  font-size: 12px;
  color: #f4976c;
  transition: all 0.3s ease;
  display: inline-block;
  text-decoration: none;
  cursor: pointer;
  margin-right: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  padding: 5px 12px;
  border-radius: 8px;
  background-color: #f8f9fa;
  color: #333;
  border: none;
  transition: all 0.2s;
  margin-left: 8px;
  font-size: 12px;
}

/* =============================== */

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  color: #333;
}

.card-header h3 i {
  margin-right: 8px;
  color: #0084ff;
}

/* 视图切换器 */
.view-switcher {
  display: flex;
  gap: 8px;
}

.view-switcher .el-button {
  padding: 4px 10px;
  border-radius: 12px;
  background-color: #f8f9fa;
  border: none;
  color: #666;
}

.view-switcher .el-button.look-view-type {
  background-color: #12884a;
  color: #fff;
}

.view-switcher .el-button.reload-data {
  background-color: #ae5ef2;
  color: #fff;
}

.view-switcher .el-button.active {
  background-color: #0084ff;
  color: #fff;
}

/* 日程列表样式 */
.schedule-list {
  list-style: none;
  padding: 0 10px 0 0;
  margin: 0;
  max-height: 400px;
  overflow-y: auto;
}

/* 滚动条样式优化 */
.schedule-list::-webkit-scrollbar {
  width: 6px;
}

.schedule-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.schedule-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.schedule-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 日期分组样式 */
.date-item-div {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  /*  border-left: 6px solid transparent;
    border-left-color: #3498db;*/
}

/* 日期标题样式 */
.date-title {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #f0f7ff;
  border-left: 6px solid #3498db;
  margin-bottom: 12px;
}

.schedule-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px dashed #f0f0f0;
  align-items: center;
}

.schedule-item:last-child {
  border-bottom: none;
}

.time {
  width: 90px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.content {
  flex: 1;
  font-size: 14px;
  color: #555;
}

.platform {
  display: inline-block;
  margin-left: 8px;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #e8f4ff;
  color: #0084ff;
  font-size: 12px;
}

.platform-wait {
  display: inline-block;
  margin-left: 8px;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #f29d72;
  color: #ffffff;
  font-size: 12px;
}

.platform-close {
  background-color: #ff4d4f;
}

.platform-end {
  background-color: #7bc47f;
}

.platform-postponement {
  background-color: #ef5c25;
}

/* 待处理数量徽章 */
.badge {
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  border-radius: 50%;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .left-column {
    width: 100%;
  }
}

.forget-div-btn {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;

  .forget-del {
    position: relative;
    font-size: 12px;
    color: #f4976c;
    transition: all 0.3s ease;
    display: inline-block;
    text-decoration: none;
    cursor: pointer;
  }

  /* 悬停时变化颜色和缩放 */

  .forget-del:hover {
    color: #ff0003;
    transform: scale(1.2);
  }

  /* 提示文字（初始隐藏） */

  .forget-del::after {
    content: "删除";
    position: absolute;
    top: -28px; /* 调整垂直位置 */
    left: 50%;
    transform: translateX(-50%) scale(0.8);
    background: rgba(255, 0, 0, 0.75);
    color: #ffffff;
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 6px;
    white-space: nowrap;
    opacity: 0;
    pointer-events: none;
    transition: all 0.25s ease;
  }

  /* 悬停或获得焦点时显示提示 */

  .forget-del:hover::after,
  .forget-del:focus::after {
    opacity: 1;
    transform: translateX(-50%) scale(1);
    top: -32px;
  }
}

.action-btn {
  display: flex;
  align-items: center;
  padding: 5px 20px;
  border-radius: 8px;
  background-color: #f8f9fa;
  color: #333;
  border: none;
  transition: all 0.2s;
}

.action-btn:hover {
  background-color: #e9ecef;
  color: #0084ff;
}

.action-btn i {
  margin-right: 8px;
  font-size: 12px;
}

.action-btn span {
  font-size: 12px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-state i {
  font-size: 48px;
  color: #ddd;
  margin-bottom: 15px;
}

.empty-state p {
  margin: 0 0 20px 0;
  color: #999;
  font-size: 16px;
}
</style>
